package com.xingkeduo.service.api.activity.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.xingkeduo.dao.TActivityDaysMapper;
import com.xingkeduo.dao.TActivityMapper;
import com.xingkeduo.dao.TActivityUseHistoryMapper;
import com.xingkeduo.dao.TMarketingCardMapper;
import com.xingkeduo.dao.TMarketingCouponBagMapper;
import com.xingkeduo.dao.TMarketingCouponMapper;
import com.xingkeduo.dao.TMarketingReceiveHistoryCardMapper;
import com.xingkeduo.dao.TMarketingReceiveHistoryCouponBagMapper;
import com.xingkeduo.dao.TMarketingReceiveHistoryCouponMapper;
import com.xingkeduo.feign.HairstyleFeignService;
import com.xingkeduo.feign.OrderFeignService;
import com.xingkeduo.model.example.TActivityDaysExample;
import com.xingkeduo.model.example.TActivityExample;
import com.xingkeduo.model.example.TActivityExample.Criteria;
import com.xingkeduo.model.example.TActivityUseHistoryExample;
import com.xingkeduo.model.example.TMarketingReceiveHistoryCardExample;
import com.xingkeduo.model.example.TMarketingReceiveHistoryCouponBagExample;
import com.xingkeduo.model.example.TMarketingReceiveHistoryCouponExample;
import com.xingkeduo.model.param.ActivityCombinationParam;
import com.xingkeduo.model.param.ActivityParam.ActivityModeEnum;
import com.xingkeduo.model.param.ActivityParam.ActivityTypeEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingReceiveTypeEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingServiceTypeEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingStatusEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingTypeEnum;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam.AuthStatusEnum;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam.MarketingReceiveStatusEnum;
import com.xingkeduo.model.po.TActivity;
import com.xingkeduo.model.po.TActivityDays;
import com.xingkeduo.model.po.TMarketing;
import com.xingkeduo.model.po.TMarketingReceiveHistory;
import com.xingkeduo.model.po.TMarketingReceiveHistoryCard;
import com.xingkeduo.model.po.TMarketingReceiveHistoryCoupon;
import com.xingkeduo.model.po.TMarketingReceiveHistoryCouponBag;
import com.xingkeduo.model.vo.ActivityDaysResponseVo;
import com.xingkeduo.model.vo.MarketingReceiveHistoryResponseVo;
import com.xingkeduo.model.vo.UserActivityResponseVo;
import com.xingkeduo.model.vo.api.ActivityApiResponseVo;
import com.xingkeduo.service.api.activity.StoreActivityService;
import com.xingkeduo.service.api.activity.UserActivityService;
import com.xingkeduo.util.Constant;
import com.xingkeduo.util.DateUtils;

@Service
public class UserActivityServiceImpl implements UserActivityService {
	Logger logger = LoggerFactory.getLogger(UserActivityServiceImpl.class);
	@Autowired
	TActivityDaysMapper tActivityDaysMapper;
	@Autowired
	HairstyleFeignService hairstyleFeignService;
	@Autowired
	TActivityMapper tActivityMapper;
	@Autowired
	StoreActivityService storeAcitvityService;
	@Autowired
	TActivityUseHistoryMapper tActivityUseHistoryMapper;
	@Autowired
	OrderFeignService orderFeignService;
	@Autowired
	TMarketingReceiveHistoryCouponMapper tMarketingReceiveHistoryCouponMapper;
	@Autowired
	TMarketingReceiveHistoryCardMapper tMarketingReceiveHistoryCardMapper;
	@Autowired
	TMarketingReceiveHistoryCouponBagMapper tMarketingReceiveHistoryCouponBagMapper;
	@Autowired
	TMarketingCouponMapper tMarketingCouponMapper;
	@Autowired
	TMarketingCardMapper tMarketingCardMapper;
	@Autowired
	TMarketingCouponBagMapper tMarketingCouponBagMapper;

	@Override
	public void getUserAvailableStoreActivity(ActivityCombinationParam param, UserActivityResponseVo userActivity) {
		// 获取指定时间内该门店下所有的活动
		List<TActivity> activityList = getAllStoreActivity(param.getStoreId(), param.getAppointmentDate());
		if(CollectionUtils.isEmpty(activityList)) {
			return;
		}
		// 重新组装数据，按照可用不可用重新分组
		for (TActivity activity : activityList) {
			if (activity.getActivityMode().intValue() == ActivityModeEnum.STORE.getCode()) {
				ActivityApiResponseVo response = this.buildNewActivityResponse(activity, param.getStoreId(),
						param.getUserId(), param.getUserType(), param.getHairServiceId(),
						param.getHairServiceOriginPrice(), param.getAppointmentDate());
				if (response.getIsAvailable() == Constant.STATUS_NO) {
					userActivity.getUnavailableActivityList().add(response);
				} else {
					userActivity.getAvailableActivityList().add(response);
				}
			}
			// 排除掉门店内其他发型师的专属活动
			if (activity.getActivityMode().intValue() == ActivityModeEnum.HAIRDRESSER.getCode()
					&& activity.getHairStyleId().equals(param.getHairdresserId())) {
				ActivityApiResponseVo response = this.buildNewActivityResponse(activity, param.getStoreId(),
						param.getUserId(), param.getUserType(), param.getHairServiceId(),
						param.getHairServiceOriginPrice(), param.getAppointmentDate());
				if (response.getIsAvailable() == Constant.STATUS_NO) {
					userActivity.getUnavailableActivityList().add(response);
				} else {
					userActivity.getAvailableActivityList().add(response);
				}
			}
		}
	}

	@Override
	public void getUserAvailableCouponActivity(ActivityCombinationParam param, UserActivityResponseVo userActivity) {
		// 获取指定时间内该用户可使用的所有卡，券
		List<TMarketingReceiveHistory> historyList = getAllUserActivity(param.getUserIds(),
				MarketingTypeEnum.COUPON.getCode(), new Date());
		if(CollectionUtils.isEmpty(historyList)) {
			return;
		}
		// 重新组装数据，按照可用不可用重新分组
		for (TMarketingReceiveHistory history : historyList) {
			MarketingReceiveHistoryResponseVo response = buildNewMarketingResponse(history, param.getStoreId(),
					param.getHairServiceId(), param.getHairServiceOriginPrice(), new Date());
			if (response.getIsAvailable() == Constant.STATUS_NO) {
				userActivity.getUnavailableCouponList().add(response);
			} else {
				userActivity.getAvailableCouponList().add(response);
			}
		}
	}
	
	@Override
	public void getUserAvailableCardActivity(ActivityCombinationParam param, UserActivityResponseVo userActivity) {
		// 获取指定时间内该用户可使用的所有卡，券
		List<TMarketingReceiveHistory> historyList = getAllUserActivity(param.getUserIds(),
				MarketingTypeEnum.CARD.getCode(), new Date());
		if(CollectionUtils.isEmpty(historyList)) {
			return;
		}
		// 重新组装数据，按照可用不可用重新分组
		for (TMarketingReceiveHistory history : historyList) {
			MarketingReceiveHistoryResponseVo response = buildNewMarketingResponse(history, param.getStoreId(),
					param.getHairServiceId(), param.getHairServiceOriginPrice(), new Date());
			if (response.getIsAvailable() == Constant.STATUS_NO) {
				userActivity.getUnavailableCardList().add(response);
			} else {
				userActivity.getAvailableCardList().add(response);
			}
		}
	}

	@Override
	public MarketingReceiveHistoryResponseVo buildNewMarketingResponse(TMarketingReceiveHistory history, Long storeId,
			Long hairServiceId, BigDecimal hairServiceOriginPrice, Date appointmentDate) {
		MarketingReceiveHistoryResponseVo vo = new MarketingReceiveHistoryResponseVo();
		BeanUtils.copyProperties(history, vo);
		TMarketing marketing = selectMarketingByPrimaryKey(history.getMarketingId(),history.getMarketingType());
		vo.setStoreNames(marketing.getStoreNames());
		vo.setPreferentialUndertakeType(marketing.getPreferentialUndertakeType() == null ? 0 : marketing.getPreferentialUndertakeType());
		vo.setHeadquartersPreferentialUndertake(marketing.getHeadquartersPreferentialUndertake() == null ? BigDecimal.valueOf(0) : marketing.getHeadquartersPreferentialUndertake());
		String marketingTypeName = MarketingTypeEnum.parseStatus(history.getMarketingType()).getDesc();
		// 状态验证
		if (MarketingReceiveStatusEnum.AVAILABLE.getCode() != history.getStatus().intValue()) {
			vo.setIsAvailable(Constant.STATUS_NO);
			vo.setUnusableReason("当前"+marketingTypeName+"已使用");
			return vo;
		}
		// 使用时间验证
		if (history.getUseStartTime().after(appointmentDate) || history.getUseEndTime().before(appointmentDate)) {
			vo.setIsAvailable(Constant.STATUS_NO);
			vo.setUnusableReason("当前"+marketingTypeName+"有效使用时间为:" + DateUtils.formatDate(history.getUseStartTime(), DateUtils.DATE_FORMAT) + "至"
					+ DateUtils.formatDate(history.getUseEndTime(), DateUtils.DATE_FORMAT));
			return vo;
		}
		// 使用门槛验证
		if (history.getLeastCost().compareTo(hairServiceOriginPrice) > 0) {
			vo.setIsAvailable(Constant.STATUS_NO);
			vo.setUnusableReason("当前"+marketingTypeName+"最低消费金额为:" + history.getLeastCost().setScale(2, BigDecimal.ROUND_HALF_UP) + "元");
			return vo;
		}
		// 适用门店校验
		String storeIds = marketing.getStoreIds();
		if (!storeIds.equals("0") && (!storeIds.contains("," + storeId + ","))) {
			vo.setIsAvailable(Constant.STATUS_NO);
			vo.setUnusableReason("当前"+marketingTypeName+"不支持该门店");
			return vo;
		}
		// 适用服务校验
		String servprodIds = marketing.getSupportServprodIds();
		if (!servprodIds.equals("0") && (!servprodIds.contains("," + hairServiceId + ","))) {
			vo.setIsAvailable(Constant.STATUS_NO);
			vo.setUnusableReason("当前"+marketingTypeName+"不支持该发型服务");
			return vo;
		}
		// 使用上限验证-活动上限，单人日上限，单人累积上限
		if (history.getInitUseLimit() != 0 && history.getCurrentUseLimit() >= history.getInitUseLimit()) {
			vo.setIsAvailable(Constant.STATUS_NO);
			vo.setUnusableReason("当前"+marketingTypeName+"已使用完");
			return vo;
		}
		// 免费卡需要验证是否通过卡认证
//		if (history.getMarketingType().intValue() == MarketingTypeEnum.CARD.getCode()
//				&& history.getServiceType().equalsIgnoreCase(MarketingServiceTypeEnum.FREE.getType())
//				&& history.getAuthStatus() != AuthStatusEnum.AUTHENTICATED.getCode()) {
//			vo.setIsAvailable(Constant.STATUS_NO);
//			vo.setUnusableReason("当前"+marketingTypeName+"未认证");
//			return vo;
//		}
//		if (history.getMarketingType().intValue() == MarketingTypeEnum.CARD.getCode()
//				&& history.getServiceType().equalsIgnoreCase(MarketingServiceTypeEnum.DISCOUNT.getType())
//				&& history.getCouponAmount().compareTo(BigDecimal.valueOf(0))==0
//				&& history.getAuthStatus() != AuthStatusEnum.AUTHENTICATED.getCode()) {
//			vo.setIsAvailable(Constant.STATUS_NO);
//			vo.setUnusableReason("当前"+marketingTypeName+"未认证");
//			return vo;
//		}
		// 是否有未服务订单
		if (history.getMarketingType().intValue() == MarketingTypeEnum.CARD.getCode()
				&& history.getServiceType().equalsIgnoreCase(MarketingServiceTypeEnum.FREE.getType())
				//&& history.getAuthStatus() != AuthStatusEnum.AUTHENTICATED.getCode()
				) {
			String orderResultStr = orderFeignService.cardTicket(history.getUserId() + "", history.getId() + "",MarketingTypeEnum.parseStatus(history.getMarketingType()).getOrderCode()+"");
			if (StringUtils.isNotBlank(orderResultStr)) {
				JSONObject message = JSON.parseObject(orderResultStr);
				String status = message.getOrDefault("status", "0") == null ? "0"
						: message.getOrDefault("status", "0").toString();
				if ("1".equals(status)) {
					Boolean cardTickFlag = message.getObject("data", Boolean.class);
					if (cardTickFlag) {
						vo.setIsAvailable(Constant.STATUS_NO);
						vo.setUnusableReason("当前"+marketingTypeName+"有未结束订单");
						return vo;
					}
				} else {
					vo.setIsAvailable(Constant.STATUS_NO);
					String msg = message.getOrDefault("msg", "查询过往订单异常") == null ? "查询过往订单异常"
							: message.getOrDefault("msg", "查询过往订单异常").toString();
					vo.setUnusableReason(msg);
					return vo;
				}
			}
		}
		if (marketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON.getCode()) {
			if (marketing.getUseLimitDay() != 0) {
				TMarketingReceiveHistoryCouponExample example = new TMarketingReceiveHistoryCouponExample();
				example.createCriteria().andUserIdEqualTo(history.getUserId())
						.andMarketingIdEqualTo(history.getMarketingId())
						.andStatusEqualTo(MarketingReceiveStatusEnum.USED.getCode())
						.andUseTimeGreaterThanOrEqualTo(DateUtils.getCurdate(appointmentDate));
				if (marketing.getUseLimitDay() <= tMarketingReceiveHistoryCouponMapper.countByExample(example)) {
					vo.setIsAvailable(Constant.STATUS_NO);
					vo.setUnusableReason("当前"+marketingTypeName+"已超出当日使用上限");
					return vo;
				}
			}
//			if (marketing.getUseLimitTotal() != 0) {
//				TMarketingReceiveHistoryCouponExample example = new TMarketingReceiveHistoryCouponExample();
//				example.createCriteria().andUserIdEqualTo(history.getUserId())
//						.andMarketingIdEqualTo(history.getMarketingId())
//						.andStatusEqualTo(MarketingReceiveStatusEnum.USED.getCode());
//				if (marketing.getUseLimitTotal() <= tMarketingReceiveHistoryCouponMapper.countByExample(example)) {
//					vo.setIsAvailable(Constant.STATUS_NO);
//					vo.setUnusableReason("当前"+marketingTypeName+"已超出个人使用上限");
//					return vo;
//				}
//			}
		}
		// 活动时间校验
		if (StringUtils.isNotBlank(marketing.getWeekHourIds()) && (!"0".equals(marketing.getWeekHourIds()))) {
			int day = DateUtils.getDayofweek(appointmentDate);
			TActivityDaysExample example = new TActivityDaysExample();
			example.createCriteria().andActivityIdEqualTo(marketing.getId())
					.andActivityTypeEqualTo(marketing.getMarketingType()).andStartTimeLessThanOrEqualTo(appointmentDate)
					.andEndTimeGreaterThanOrEqualTo(appointmentDate).andStatusEqualTo(Constant.STATUS_YES)
					.andDayidsLike("%" + day + "%");
			int count = tActivityDaysMapper.countByExample(example);
			if (count <= 0) {
				vo.setIsAvailable(Constant.STATUS_NO);
				vo.setUnusableReason("当前"+marketingTypeName+"仅限指定时间段内使用");
				return vo;
			}
		}
		vo.setIsAvailable(Constant.STATUS_YES);
		return vo;
	}

	private List<TMarketingReceiveHistory> getAllUserActivity(List<Long> userIdList, Integer marketingType,
			Date appointmentDate) {
		//查询券
		if (marketingType.intValue() == MarketingTypeEnum.COUPON.getCode()) {
			TMarketingReceiveHistoryCouponExample example = new TMarketingReceiveHistoryCouponExample();
			example.createCriteria().andUserIdIn(userIdList).andMarketingTypeEqualTo(marketingType)
					.andStatusEqualTo(MarketingReceiveStatusEnum.AVAILABLE.getCode())
					//.andUseStartTimeLessThanOrEqualTo(appointmentDate)
					.andUseEndTimeGreaterThanOrEqualTo(appointmentDate);
			List<TMarketingReceiveHistoryCoupon> couponList = tMarketingReceiveHistoryCouponMapper
					.selectByExample(example);
			if (!CollectionUtils.isEmpty(couponList)) {
				return Lists.transform(couponList,
						new Function<TMarketingReceiveHistoryCoupon, TMarketingReceiveHistory>() {
							@Override
							public TMarketingReceiveHistory apply(TMarketingReceiveHistoryCoupon history) {
								return history;
							}
						});
			}
		}
		//查询卡
		if (marketingType.intValue() == MarketingTypeEnum.CARD.getCode()) {
			TMarketingReceiveHistoryCardExample example = new TMarketingReceiveHistoryCardExample();
			example.createCriteria().andUserIdIn(userIdList).andMarketingTypeEqualTo(marketingType)
					.andStatusEqualTo(MarketingReceiveStatusEnum.AVAILABLE.getCode())
					//.andUseStartTimeLessThanOrEqualTo(appointmentDate)
					.andUseEndTimeGreaterThanOrEqualTo(appointmentDate);
			List<TMarketingReceiveHistoryCard> cardList = tMarketingReceiveHistoryCardMapper.selectByExample(example);
			if (!CollectionUtils.isEmpty(cardList)) {
				return Lists.transform(cardList,
						new Function<TMarketingReceiveHistoryCard, TMarketingReceiveHistory>() {
							@Override
							public TMarketingReceiveHistory apply(TMarketingReceiveHistoryCard history) {
								return history;
							}
						});
			}
		}
		//查询券包
		if (marketingType.intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
			TMarketingReceiveHistoryCouponBagExample example = new TMarketingReceiveHistoryCouponBagExample();
			example.createCriteria().andUserIdIn(userIdList).andMarketingTypeEqualTo(marketingType)
					.andStatusEqualTo(MarketingReceiveStatusEnum.AVAILABLE.getCode())
					//.andUseStartTimeLessThanOrEqualTo(appointmentDate)
					.andUseEndTimeGreaterThanOrEqualTo(appointmentDate);
			List<TMarketingReceiveHistoryCouponBag> couponBagList = tMarketingReceiveHistoryCouponBagMapper
					.selectByExample(example);
			if (!CollectionUtils.isEmpty(couponBagList)) {
				return Lists.transform(couponBagList,
						new Function<TMarketingReceiveHistoryCouponBag, TMarketingReceiveHistory>() {
							@Override
							public TMarketingReceiveHistory apply(TMarketingReceiveHistoryCouponBag history) {
								return history;
							}
						});
			}
		}
		return null;
	}

	private List<TActivity> getAllStoreActivity(Long storeId, Date appointmentDate) {
		return getAllStoreActivity(storeId, appointmentDate, appointmentDate);
	}

	private List<TActivity> getAllStoreActivity(Long storeId, Date startDate, Date endDate) {
		List<TActivity> activityList = new ArrayList<TActivity>();
		// 查询设置部分门店的活动中是否包含本门店
		TActivityExample someActivityExample = new TActivityExample();
		Criteria criteria = someActivityExample.createCriteria();
		criteria.andStartTimeLessThanOrEqualTo(endDate).andEndTimeGreaterThanOrEqualTo(startDate)
				.andActivityTypeNotEqualTo(ActivityTypeEnum.HELP_PAYMENT.getStatusType())
				.andStatusEqualTo(MarketingStatusEnum.UP.getCode()).andStoreIdsLike("%," + storeId + ",%");
		List<TActivity> someActivityList = tActivityMapper.selectByExample(someActivityExample);
		if (!CollectionUtils.isEmpty(someActivityList)) {
			activityList.addAll(someActivityList);
		}
		// 查询设置全门店的活动中是否包含本门店
		TActivityExample allActivityExample = new TActivityExample();
		Criteria allCriteria = allActivityExample.createCriteria();
		allCriteria.andStartTimeLessThanOrEqualTo(endDate).andEndTimeGreaterThanOrEqualTo(startDate)
				.andActivityTypeNotEqualTo(ActivityTypeEnum.HELP_PAYMENT.getStatusType())
				.andStatusEqualTo(MarketingStatusEnum.UP.getCode()).andStoreIdsEqualTo("0");
		List<TActivity> allActivityList = tActivityMapper.selectByExample(allActivityExample);
		// 本店下所有的优惠活动
		if (!CollectionUtils.isEmpty(allActivityList)) {
			activityList.addAll(allActivityList);
		}
//		.stream()
//		.collect(Collectors.collectingAndThen(
//				Collectors
//						.toCollection(() -> new TreeSet<>(Comparator.comparing(activity -> activity.getId()))),
//				ArrayList::new));
		return activityList;
	}

	@Override
	public ActivityApiResponseVo buildNewActivityResponse(TActivity activity, Long storeId, Long userId,
			Integer userType, Long hairServiceId, BigDecimal hairServiceOriginPrice, Date appointmentDate) {
		ActivityApiResponseVo vo = new ActivityApiResponseVo();
		BeanUtils.copyProperties(activity, vo);
		// 状态验证
		if (activity == null || MarketingStatusEnum.UP.getCode() != activity.getStatus().intValue()) {
			vo.setIsAvailable(Constant.STATUS_NO);
			vo.setUnusableReason("当前活动尚未上线");
			return vo;
		}
		// 库存验证
		if (activity.getStockQuantity() != null && activity.getStockQuantity().intValue() != 0
				&& activity.getSurplusQuantity().intValue() <= 0) {
			vo.setIsAvailable(Constant.STATUS_NO);
			vo.setUnusableReason("当前活动以抢完");
			return vo;
		}
		// 使用时间验证
		if (activity.getStartTime().after(appointmentDate) || activity.getEndTime().before(appointmentDate)) {
			vo.setIsAvailable(Constant.STATUS_NO);
			vo.setUnusableReason("当前活动有效时间为:" + DateUtils.formatDate(activity.getStartTime(), DateUtils.DATE_FORMAT)
					+ "至" + DateUtils.formatDate(activity.getStartTime(), DateUtils.DATE_FORMAT));
			return vo;
		}
		// 使用门槛校验
		if (activity.getLeastCost().compareTo(hairServiceOriginPrice) > 0) {
			vo.setIsAvailable(Constant.STATUS_NO);
			vo.setUnusableReason("当前活动最低消费金额为:" + activity.getLeastCost().setScale(2, BigDecimal.ROUND_HALF_UP) + "元");
			return vo;
		}
		// 适用门店校验
		String storeIds = activity.getStoreIds();
		if (StringUtils.isNotBlank(storeIds) && (!storeIds.equals("0")) && (!storeIds.contains("," + storeId + ","))) {
			vo.setIsAvailable(Constant.STATUS_NO);
			vo.setUnusableReason("当前活动不支持该门店");
			return vo;
		}
		// 适用服务校验
		String servprodIds = activity.getSupportServprodIds();
		if (StringUtils.isNotBlank(servprodIds) && (!servprodIds.equals("0"))
				&& (!servprodIds.contains("," + hairServiceId + ","))) {
			vo.setIsAvailable(Constant.STATUS_NO);
			vo.setUnusableReason("当前活动不支持该发型服务");
			return vo;
		}
		// 使用上限验证-活动上限，单人日上限，单人累积上限
		if (activity.getUseLimitDay() != 0) {
			TActivityUseHistoryExample example = new TActivityUseHistoryExample();
			example.createCriteria().andUserIdEqualTo(userId).andActivityIdEqualTo(activity.getId())
					.andStatusEqualTo(Constant.STATUS_YES)
					.andCreateTimeGreaterThanOrEqualTo(DateUtils.getCurdate(appointmentDate));
			if (activity.getUseLimitDay() <= tActivityUseHistoryMapper.countByExample(example)) {
				vo.setIsAvailable(Constant.STATUS_NO);
				vo.setUnusableReason("当前活动已超出日使用上限");
				return vo;
			}
		}
		if (activity.getUseLimitTotal() != 0) {
			TActivityUseHistoryExample example = new TActivityUseHistoryExample();
			example.createCriteria().andUserIdEqualTo(userId).andActivityIdEqualTo(activity.getId())
					.andStatusEqualTo(Constant.STATUS_YES);
			if (activity.getUseLimitTotal() <= tActivityUseHistoryMapper.countByExample(example)) {
				vo.setIsAvailable(Constant.STATUS_NO);
				vo.setUnusableReason("当前活动已超出个人使用上限");
				return vo;
			}
		}
		if (activity.getStockQuantity() != 0 && activity.getSurplusQuantity() <= 0) {
			vo.setIsAvailable(Constant.STATUS_NO);
			vo.setUnusableReason("当前活动已抢完");
			return vo;
		}
		// 用户参与范围校验
		MarketingReceiveTypeEnum marketingReceiveTypeEnum = MarketingReceiveTypeEnum
				.parseStatus(activity.getReceiveType());
		switch (marketingReceiveTypeEnum) {
		case ALL:
			break;
		case STORE_NEW:
			if (userType.intValue() == MarketingReceiveTypeEnum.ALL.getCode()) {
				vo.setIsAvailable(Constant.STATUS_NO);
				vo.setUnusableReason("当前活动仅限门店新用户使用");
				return vo;
			}
			break;
		case PLATFORM_NEW:
			if (userType.intValue() != MarketingReceiveTypeEnum.PLATFORM_NEW.getCode()) {
				vo.setIsAvailable(Constant.STATUS_NO);
				vo.setUnusableReason("当前活动仅限新用户使用");
				return vo;
			}
			break;
		default:
			break;
		}
		// 活动时间校验
		if (StringUtils.isNotBlank(activity.getWeekHourIds()) && (!"0".equals(activity.getWeekHourIds()))) {
			int day = DateUtils.getDayofweek(appointmentDate);
			TActivityDaysExample example = new TActivityDaysExample();
			example.createCriteria().andActivityIdEqualTo(activity.getId())
					.andActivityTypeEqualTo(activity.getActivityMode()).andStartTimeLessThanOrEqualTo(appointmentDate)
					.andEndTimeGreaterThanOrEqualTo(appointmentDate).andStatusEqualTo(Constant.STATUS_YES)
					.andDayidsLike("%" + day + "%");
			int count = tActivityDaysMapper.countByExample(example);
			if (count <= 0) {
				vo.setIsAvailable(Constant.STATUS_NO);
				vo.setUnusableReason("当前活动仅限指定时间段内使用");
				return vo;
			}
			if (activity.getActivityType().equals(ActivityTypeEnum.BYPASS_FLOW.getStatusType())) {
				List<TActivityDays> activityDays = tActivityDaysMapper.selectByExample(example);
				activity.setActivityAmount(activityDays.get(0).getActivityAmount());
				vo.setActivityAmount(activity.getActivityAmount());
			}
		}
		vo.setIsAvailable(Constant.STATUS_YES);
		return vo;
	}

	@Override
	public void getUserAvailableStoreBypassFlowActivity(ActivityCombinationParam param,
			UserActivityResponseVo userActivity) {
		// 获取指定时间内该门店下所有的活动
		List<TActivity> activityList = getAllStoreActivity(param.getStoreId(), param.getAppointmentDate());
		if(CollectionUtils.isEmpty(activityList)) {
			return;
		}
		// 重新组装数据，按照可用不可用重新分组
		for (TActivity activity : activityList) {
			if (!ActivityTypeEnum.BYPASS_FLOW.getStatusType().equalsIgnoreCase(activity.getActivityType())) {
				continue;
			}
			if (activity.getActivityMode().intValue() == ActivityModeEnum.STORE.getCode()) {
				ActivityApiResponseVo response = this.buildNewActivityResponse(activity, param.getStoreId(),
						param.getUserId(), param.getUserType(), param.getHairServiceId(),
						param.getHairServiceOriginPrice(), param.getAppointmentDate());
				if (response.getIsAvailable() == Constant.STATUS_YES) {
					userActivity.getAvailableActivityList().add(response);
					return;
				}
			}
			// 排除掉门店内其他发型师的专属活动
			if (activity.getActivityMode().intValue() == ActivityModeEnum.HAIRDRESSER.getCode()
					&& activity.getHairStyleId().equals(param.getHairdresserId())) {
				ActivityApiResponseVo response = this.buildNewActivityResponse(activity, param.getStoreId(),
						param.getUserId(), param.getUserType(), param.getHairServiceId(),
						param.getHairServiceOriginPrice(), param.getAppointmentDate());
				if (response.getIsAvailable() == Constant.STATUS_YES) {
					userActivity.getAvailableActivityList().add(response);
					return;
				}
			}
		}
	}

	@Override
	public Map getStoreAvailableStoreBypassFlowActivity(Long storeId, Long hairdresserId, Long hairServiceId,
			Date startDate, Date endDate) {
		Map responseMap = new HashMap();
		// 获取指定时间内该门店下所有的活动
		List<TActivity> activityList = getAllStoreActivity(storeId, startDate, endDate);
		if(CollectionUtils.isEmpty(activityList)) {
			return responseMap;
		}
		for (TActivity activity : activityList) {
			// 仅仅查询分流活动
			if (!ActivityTypeEnum.BYPASS_FLOW.getStatusType().equalsIgnoreCase(activity.getActivityType())) {
				continue;
			}
			// 不支持该发型师
			if (activity.getActivityMode().intValue() == ActivityModeEnum.HAIRDRESSER.getCode()
					&& (!activity.getHairStyleId().equals(hairdresserId))) {
				continue;
			}

			Date sDate = startDate;
			Date eDate = endDate;
			while (sDate.before(eDate) || sDate.equals(eDate)) {
				ActivityApiResponseVo response = this.buildNewActivityResponse(activity, storeId, hairServiceId, sDate);
				if (response != null) {
					responseMap.put(DateUtils.formatDate(sDate, DateUtils.DATE_FORMAT), response);
				}
				sDate = DateUtils.addSomeDays(sDate, 1);
			}
		}
		return responseMap;
	}

	private ActivityApiResponseVo buildNewActivityResponse(TActivity activity, Long storeId, Long hairServiceId,
			Date startDate) {
		ActivityApiResponseVo vo = new ActivityApiResponseVo();
		BeanUtils.copyProperties(activity, vo);
		// 状态验证
		if (activity == null || MarketingStatusEnum.UP.getCode() != activity.getStatus().intValue()) {
			return null;
		}
		// 库存验证
		if (activity.getStockQuantity() != null && activity.getStockQuantity().intValue() != 0
				&& activity.getSurplusQuantity().intValue() <= 0) {
			vo.setIsAvailable(Constant.STATUS_NO);
			vo.setUnusableReason("当前活动已抢完");
			return vo;
		}
		// 使用时间验证
		if (DateUtils.getCurdate(activity.getStartTime()).after(startDate) || activity.getEndTime().before(startDate)) {
			return null;
		}
		// 适用门店校验
		String storeIds = activity.getStoreIds();
		if (StringUtils.isNotBlank(storeIds) && (!storeIds.equals("0")) && (!storeIds.contains("," + storeId + ","))) {
			return null;
		}
		// 适用服务校验
		String servprodIds = activity.getSupportServprodIds();
		if (StringUtils.isNotBlank(servprodIds) && (!servprodIds.equals("0"))
				&& (!servprodIds.contains("," + hairServiceId + ","))) {
			return null;
		}
		if (activity.getStockQuantity() != 0 && activity.getSurplusQuantity() <= 0) {
			return null;
		}
		// 活动时间校验
		if (StringUtils.isNotBlank(activity.getWeekHourIds()) && (!"0".equals(activity.getWeekHourIds()))) {
			int day = DateUtils.getDayofweek(startDate);
			TActivityDaysExample example = new TActivityDaysExample();
			example.createCriteria().andActivityIdEqualTo(activity.getId())
					.andActivityTypeEqualTo(activity.getActivityMode()).andStatusEqualTo(Constant.STATUS_YES)
					.andDayidsLike("%" + day + "%");
			List<TActivityDays> activityDaysList = tActivityDaysMapper.selectByExample(example);
			if (CollectionUtils.isEmpty(activityDaysList)) {
				return null;
			}
			List<ActivityDaysResponseVo> activityDaysResponseVoList = Lists.transform(activityDaysList,
					new Function<TActivityDays, ActivityDaysResponseVo>() {
						@Override
						public ActivityDaysResponseVo apply(TActivityDays activityDays) {
							ActivityDaysResponseVo activityDaysResponseVo = new ActivityDaysResponseVo();
							BeanUtils.copyProperties(activityDays, activityDaysResponseVo);
							return activityDaysResponseVo;
						}
					});
			vo.setActivityDays(activityDaysResponseVoList);
		}
		return vo;
	}

	private TMarketing selectMarketingByPrimaryKey(Long marketingId, Integer marketingType) {
		if (marketingType.equals(MarketingTypeEnum.COUPON.getCode())) {
			return tMarketingCouponMapper.selectByPrimaryKey(marketingId);
		} else if (marketingType.equals(MarketingTypeEnum.CARD.getCode())) {
			return tMarketingCardMapper.selectByPrimaryKey(marketingId);
		} else if (marketingType.equals(MarketingTypeEnum.COUPON_BAG.getCode())) {
			return tMarketingCouponBagMapper.selectByPrimaryKey(marketingId);
		}
		return null;
	}
}
